package org.feng.config;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.IllegalSQLInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.feng.interceptor.MybatisPlusSensitiveInterceptor;
import org.feng.interceptor.MybatisPrintSqlInterceptor;
import org.feng.properties.MybatisInterceptorProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * Mybatis-Plus插件之拦截器的自动配置类<br>
 * <a href="https://baomidou.com/pages/2976a3/#mybatisplusinterceptor">插件官网链接</a>
 *
 * @version v1.0
 * @author: fengjinsong
 * @date: 2023年08月24日 22时01分
 */
@Slf4j
@AutoConfiguration
public class MybatisInterceptorConfiguration {

    @Resource
    private MybatisInterceptorProperties mybatisInterceptorProperties;

    /**
     * 配置拦截器
     *
     * @return 拦截器
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 自定义拦截：密文处理
        if (mybatisInterceptorProperties.isEnableSensitive()) {
            log.info("mybatis注册拦截器：密文处理");
            interceptor.addInnerInterceptor(MybatisPlusSensitiveInterceptor.builder().build());
        }

        // sql性能规范
        if (mybatisInterceptorProperties.isEnableIllegalSql()) {
            log.info("mybatis注册拦截器：SQL性能规范检查");
            interceptor.addInnerInterceptor(new IllegalSQLInnerInterceptor());
        }

        // 乐观锁
        if (mybatisInterceptorProperties.isEnableOptimisticLocker()) {
            log.info("mybatis注册拦截器：乐观锁");
            interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        }
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> {
            // SQL 打印拦截
            if (mybatisInterceptorProperties.isPrintSql()) {
                log.info("mybatis注册拦截器：打印sql");
                configuration.addInterceptor(new MybatisPrintSqlInterceptor());
            }
        };
    }


    @PostConstruct
    private void init() {
        log.info("Mybatis-Plus插件之拦截器的自动配置类 init");
    }
}
